<?php

namespace Biz\model\bizAd;

use Biz\pockets\modelTrait\BizModelTrait;
use Doraemon\pockets\datebase\BaseDbModel;

class AdPlan extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_biz_ad';

    const _CONFIG_SELECT_ = 'db_biz_ad';

    const _DATABASE_ = 'biz_ad';

    const _TABLE_NAME = 'hhz_ad_paln';

    const PLAN_FORM_CONTENT = 1;//计划形式，1：内容
    const PLAN_FORM = [//计划形式
        self::PLAN_FORM_CONTENT => '内容'
    ];

    const AD_TYPE_CPM = 1;//投放类型，1：CPM
    const AD_TYPE = [
        self::AD_TYPE_CPM => 'CPM'
    ];

    //计划状态
    const PLAN_STATUS_UNAUDITED = 0;//待审核（备用，暂未使用）
    const PLAN_STATUS_NORMAL = 1;//默认：未投放（待投放）
    const PLAN_STATUS_OPEN = 2;//已投放（已开启投放）
    const PLAN_STATUS_CANCEL = 3;//已取消
    const PLAN_STATUS_DELETE = 9;//已删除

    //计划状态-虚拟状态
    const PLAN_STATUS_START = 4;//进行中
    const PLAN_STATUS_END = 5;//已结束

    const PLAN_STATE = [
        self::PLAN_STATUS_UNAUDITED => '待审核',
        self::PLAN_STATUS_NORMAL => '-',//未投放、待投放
        self::PLAN_STATUS_OPEN => '待生效',
        self::PLAN_STATUS_CANCEL => '已取消',
        self::PLAN_STATUS_START => '生效中',
        self::PLAN_STATUS_END => '已结束',
        self::PLAN_STATUS_DELETE => '已删除'
    ];

    const SETTLE_DELAY = 5 * 60;//结算时间延迟5分钟

    //结算状态
    const SETTLE_STATUS_NORMAL = 0;//未结算
    const SETTLE_STATUS_FINISH = 1;//已结算

    const SETTLE_STATUS_MAP = [
        self::SETTLE_STATUS_NORMAL => '未结算',
        self::SETTLE_STATUS_FINISH => '已结算'
    ];

    const ONE_CPM_COUNT = 1000;//1个cpm，对应千次曝光


    use BizModelTrait;

    public static function getPlanInfo($planId)
    {
        $info = self::dataSelectInfo(['id' => $planId]);
        $info = $info ? self::formatInfo($info) : [];
        return $info;
    }

    public static function getPlanList($where)
    {
        $res = self::dataSelect($where);
        $list = [];
        foreach ($res as $row) {
            $list[$row['id']] = self::formatInfo($row);
        }
        return $list;
    }

    public static function addPlan($data)
    {
        $data['create_time'] = date('Y-m-d H:i:s');
        $id = self::dataInsert($data);
        return $id;
    }

    public static function updatePlan($planId, $data)
    {
        $data['update_time'] = date('Y-m-d H:i:s');
        return self::dataUpdate($data, ['id' => $planId]);
    }


    private static function formatInfo($info)
    {
        $now = time();
        foreach ($info as $key => $val) {
            switch ($key) {
                case 'plan_status':
                    switch ($val) {
                        case self::PLAN_STATUS_UNAUDITED:
                            $info['plan_state'] = self::PLAN_STATUS_UNAUDITED;//待审核
                            break;
                        case self::PLAN_STATUS_NORMAL:
                            $info['plan_state'] = self::PLAN_STATUS_NORMAL;//未投放
                            break;
                        case self::PLAN_STATUS_OPEN:
                            if ($info['start_time'] > $now) {
                                $info['plan_state'] = self::PLAN_STATUS_OPEN;//未开始
                            } else if ($info['start_time'] <= $now && $info['end_time'] >= $now) {
                                $info['plan_state'] = self::PLAN_STATUS_START;//进行中
                            } else if ($info['end_time'] < $now) {
                                $info['plan_state'] = self::PLAN_STATUS_END;//已结束
                            }
                            if ($info['expose_count'] >= $info['target_count']) {
                                $info['plan_state'] = self::PLAN_STATUS_END;//已结束
                            }
                            break;
                        case self::PLAN_STATUS_CANCEL:
                            $info['plan_state'] = self::PLAN_STATUS_CANCEL;//已取消
                            break;
                        case self::PLAN_STATUS_DELETE:
                            $info['plan_state'] = self::PLAN_STATUS_DELETE;//已删除
                            break;
                    }
                    $info['plan_state_desc'] = self::PLAN_STATE[$info['plan_state']];
                    break;
                case 'expose_count':
                    $info['finished_rate'] = floor(round($info['expose_count'] / $info['target_count'] * 100, 2)) . '%';//完成进度
                    break;
            }
        }
        return $info;
    }

    public static function getConditionBySettle($planSettle)
    {
        $condition = [];
        $now = time();
        switch ($planSettle) {
            case self::PLAN_STATUS_UNAUDITED:
                $condition['plan_status'] = $planSettle;
                break;
            case self::PLAN_STATUS_NORMAL:
                $condition['plan_status'] = $planSettle;
                break;
            case self::PLAN_STATUS_OPEN:
                $condition['plan_status'] = $planSettle;
                $condition['start_time[>]'] = $now;
                break;
            case self::PLAN_STATUS_CANCEL:
                $condition['plan_status'] = $planSettle;
                break;
            case self::PLAN_STATUS_START:
                $condition = [
                    'plan_status' => self::PLAN_STATUS_OPEN,
                    'expose_count[<]' => \Medoo\Medoo::raw('`target_count`'),
                    'start_time[<]' => $now,
                    'end_time[>]' => $now,
                ];
                break;
            case self::PLAN_STATUS_END:
                $condition['plan_status'] = self::PLAN_STATUS_OPEN;
                $condition['OR'] = [
                    'end_time[<]' => $now,
                    'expose_count[>=]' => \Medoo\Medoo::raw('`target_count`')
                ];
                break;
            case self::PLAN_STATUS_DELETE:
                $condition['plan_status'] = $planSettle;
                break;
        }
        return $condition;
    }

    /**
     * 获取计划状态（虚拟）
     * @param $planInfo
     * @return mixed
     */
    public static function getPlanState($planInfo){
        $planInfo = self::formatInfo($planInfo);
        return $planInfo['plan_state'];
    }

}